package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.Reconciliation;
import com.xmy.cultivate.entity.views.ResTransaction;
import com.xmy.cultivate.enums.ArriveAffirmEnum;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.StatusOrderApplyEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.CompanyMapper;
import com.xmy.cultivate.mapper.OrderApplyMapper;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.SubjectsMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.ConfigData;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-28
 */
@Service
public class OrderApplyServiceImpl extends ServiceImpl<OrderApplyMapper, OrderApply> implements IOrderApplyService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    @Lazy
    IOrderPayAccountService iOrderPayAccountService;

    @Autowired
    @Lazy
    OrderApplyMapper orderApplyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IRenewClassService iRenewClassService;

    @Autowired
    @Lazy
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    CompanyMapper companyMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;


    /**
     *订单类型：1报名，2补费，3转课，4退费,5转校
     * @param orderApply
     * @return
     */
    @Transactional
    public boolean saveTo(OrderApply orderApply) throws ParseException {
        Integer orderType = orderApply.getOrderType().getKey();
        OrderTransfer orderTransfer = orderApply.getOrderTransfer();
        //转课
        if(orderType == Code.ORDER_TYPE_TRANSFER){
            if(orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId()) == false){
                throw new CommonException(ResultCode.SCHOOL_IN_EQUAL);
            }
        }

        orderApply.setSchoolId(orderApply.getHandleSchoolId());//所属校区
        //添加所属校区
        iStudentSchoolService.addOrUpdateData(orderApply.getStudentId(),orderApply.getHandleSchoolId());

        //修改学生所属校区
        Student student = iStudentService.getById(orderApply.getStudentId());
        if(student != null){
            if(!student.getSchoolId().equals(orderApply.getHandleSchoolId())){
                student.setSchoolId(orderApply.getHandleSchoolId());
                iStudentService.updateById(student);
            }
        }

        orderApplyMapper.insert(orderApply);


        //补费，转课，退费信息，防止重复提交（备注：待完成）
        if(orderType == Code.ORDER_TYPE_SUPP || orderType == Code.ORDER_TYPE_TRANSFER || orderType == Code.ORDER_TYPE_REFUND){

        }



        //****************************************补费，转课，退费信息 start***********************************//
        //转课
        if(orderType == Code.ORDER_TYPE_TRANSFER && orderTransfer!=null){
            //orderApply.setOrderType(orderType);
            orderApply.setTransferPrice(orderTransfer.getOutPrice());//转出抵扣金额
        }
        //****************************************补费，转课，退费信息 end***********************************//

        //订单类型,1报名，2补费，3转课，4退费
        if(orderType == Code.ORDER_TYPE_SiGN){
            if(orderApply.getOwnPrice() != null){
                if(orderApply.getOwnPrice().compareTo(BigDecimal.ZERO) > 0){
                    orderApply.setIsOwn(1);//设置为欠费状态
                }
            }
        }

        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元

        //2补费，3转课，4退费
        if((orderType == Code.ORDER_TYPE_TRANSFER || orderType== Code.ORDER_TYPE_SUPP || orderType == Code.ORDER_TYPE_REFUND) && orderTransfer!=null){
            orderTransfer.setOrderId(orderApply.getId());
            iOrderTransferService.save(orderTransfer);
            Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
            if(orderType == Code.ORDER_TYPE_TRANSFER){
                tradeContent += "转出："+outCourse.getName()+","+orderTransfer.getOutHouse()+"课时,"+orderTransfer.getOutPrice()+"元";
            }else if (orderType== Code.ORDER_TYPE_SUPP){
                //tradeContent += "补费："+orderTransfer.getOutPrice()+"元";

            }else if (orderType== Code.ORDER_TYPE_REFUND){
                tradeContent += "退费："+outCourse.getName()+"退"+orderTransfer.getOutHouse()+"课时，应退学费"+orderTransfer.getOutPrice()+"元";
            }
        }


        //System.out.print("insertId:"+orderApply.getId());
        //分班
        List<StudentGrade> studentGradeList = new ArrayList<>();
        //续费信息
        List<RenewClass> renewClassesList = new ArrayList<>();

        //报名与转课
        //*************************************订单详情start**************************************************//
        if(orderType == Code.ORDER_TYPE_SiGN || orderType == Code.ORDER_TYPE_TRANSFER){
            //支付详情
            List<OrderDetail> orderDetailList = new ArrayList<>();
            Iterator<OrderDetail> orderDetailIterator = orderApply.getOrderDetailList().iterator();



            while (orderDetailIterator.hasNext()){

                if(orderType == Code.ORDER_TYPE_SiGN){
                    if(tradeContent !=""){
                        tradeContent += "</br>";
                    }else {
                        tradeContent += "报名：";
                    }
                }else{
                    tradeContent += "</br>转入：";
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                orderDetail.setHandleDate(orderApply.getHandleDate());
                orderDetail.setOrderType(orderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(orderApply.getStudentId());
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//优惠金额
                //studentGrade.setSchoolId();
                //studentGrade.setEndDate();

                //studentGrade.setAllCourseCount(orderDetail.getAllCourseCount());
                //studentGrade.setUseCourseCount(0);
                //studentGrade.setResidueCourseCount(orderDetail.getAllCourseCount());
                Course course = iCourseService.getById(orderDetail.getCourseId());
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份

                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                orderDetail.setYearPart(year_part);

                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part+""+course.getQuarterNum()));



                tradeContent += course.getName()+",";

                //续班信息
                /*RenewClass renewClass = iQuarterService.getRenewForPay(orderApply.getStudentId(),orderDetail.getSchoolId(),orderDetail.getSubjectsId(),orderDetail.getCourseId(),orderDetail.getAllCourseCount(),orderType);
                renewClass.setOrderType(orderApply.getOrderType().getKey());
                if(renewClass.getReSetIsnew() == 1){
                    orderDetail.setIsNewStudent(1);//设置为新生
                }else {
                    orderDetail.setIsNewStudent(0);
                }*/

                Grade grade = null;
                if(orderDetail.getGradeId()!=null){
                    //分班
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(orderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);
                    studentGrade.setQuarterNum(course.getQuarterNum());

                    //studentGrade.setOrderDetailId(orderDetail.getId());//设置订单id
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if(grade!=null){
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        studentGrade.setSchoolId(grade.getSchoolId());
                        //orderDetail.setSchoolId(grade.getSchoolId());
                        tradeContent += grade.getName()+",";

                        //添加到班级
                        iStudentGradeService.addData(orderDetail.getId(),grade.getSchoolId(),orderApply.getStudentId(),grade.getId(),course.getId(),course.getSubjectsId(),year_part,course.getQuarterNum(),orderDetail.getAllCourseCount());

                        //设置续班老师
                        /*if(orderType == Code.ORDER_TYPE_SiGN){
                            studentGrade.setRenewTeacherId(grade.getTeacherId());
                        }else {
                            //转课
                            if(orderDetail.getAllCourseCount()>3){
                                studentGrade.setRenewTeacherId(grade.getTeacherId());
                            }
                        }*/

                    }
                    //studentGradeList.add(studentGrade);
                }

                tradeContent += orderDetail.getPrice();

                if(orderDetail.getCoursePriceId()!=null){
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if(coursePricing != null){
                        tradeContent +="("+coursePricing.getCountUnit()+")*"+orderDetail.getCount()+"="+orderDetail.getPrice()+"元";
                        orderDetail.setCoursePriceName(coursePricing.getCount()+coursePricing.getCountUnit()+"="+coursePricing.getPrice()+"元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(orderApply.getId());

                //renewClass.setOrderDetailId(orderDetail.getId());
                //renewClassesList.add(renewClass);
                //orderDetail.setYearPart(renewClass.getYearPart());
                iOrderDetailService.save(orderDetail);
                //orderDetailList.add(orderDetail);

                //设置为新生或者老生
                Company company = companyMapper.selectById(1L);
                if(company.getIsUseNewOld() == 1){
                    iStudentTypeService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course.getSubjectsId(),orderDetail.getIsNewStudent());
                }else {
                    iStudentTypeService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course.getSubjectsId(),1);
                }
                //更新续班信息是否成功
                if(orderType == Code.ORDER_TYPE_SiGN){
                    //报名
                    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),1);
                }else {
                    //转课
                    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),2);

                }

                iRenewDataService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),year_part,course,grade);

            }


            if(orderDetailList.size()>0){
                //为了添加交易内容，放在上面一条一条加
                //iOrderDetailService.saveBatch(orderDetailList,orderDetailList.size());
            }
            if(studentGradeList.size()>0){
                iStudentGradeService.saveBatch(studentGradeList,studentGradeList.size());
            }
        }

        //*************************************订单详情end**************************************************//

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = orderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()){
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(orderApply.getId());
            orderPayAccountList.add(orderPayAccount);
        }
        if(orderPayAccountList.size()>0){
            iOrderPayAccountService.saveBatch(orderPayAccountList,orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//

        //****************************************补费start***********************************//
        if(orderType == Code.ORDER_TYPE_SUPP){
            tradeContent += "补费：";
            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()){
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                //补费
                if(orderType == Code.ORDER_TYPE_SUPP){
                    UpdateWrapper<OrderApply> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id",orderTransferDetail.getOldOrderId());
                    updateWrapper.set("is_own",0);
                    orderApplyMapper.update(null,updateWrapper);

                    //交易内容
                    List<OrderDetail> orderDetailList = iOrderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id",orderTransferDetail.getOldOrderId()));
                    for (OrderDetail orderDetail:orderDetailList){
                        tradeContent += orderDetail.getCourseName()+" ";
                        tradeContent += orderTransferDetail.getInPrice()+"元";
                    }
                }
                iOrderTransferDetailService.save(orderTransferDetail);
                //orderTransferDetailList.add(orderTransferDetail);
            }
        }
        //****************************************补费end***********************************//

        //****************************************转课start***********************************//


        if(orderType == Code.ORDER_TYPE_TRANSFER){
            Long transferCourseId = null;
            //Boolean isAll = true;//是否全部转出

            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()){
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                //转课，扣除原有课时
                if(orderTransferDetail.getOutHouse() > 0){
                    OrderDetail orderDetail = orderDetailMapper.selectById(orderTransferDetail.getOldOrderDetailId());
                    if(orderDetail != null){
                        transferCourseId = orderDetail.getCourseId();
                        UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
                        Integer courseHouse = orderDetail.getResidueCourseCount() - orderTransferDetail.getOutHouse();
                        //转出课时不能大于剩余课时
                        if(courseHouse < 0){
                            throw new CommonException(ResultCode.OUT_COURSE_BIG);
                        }else if(courseHouse == 0){
                            orderDetailUpdateWrapper.set("reading_status",2);//全部转出，把课程设置为转出状态

                            StudentGrade studentGrade = iStudentGradeService.getById(orderDetail.getId());
                            if(studentGrade != null){
                                if(studentGrade.getUseCourseCount() == 0){
                                    iStudentSchoolService.removeById(studentGrade);
                                }else {
                                    //把所在班级设置为结课状态
                                    UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                                    //studentGradeUpdateWrapper.set("status",2);
                                    studentGradeUpdateWrapper.set("reading_status",ReadingStatusEnum.FINISH.getKey());
                                    studentGradeUpdateWrapper.eq("order_detail_id",orderDetail.getId());
                                    iStudentGradeService.update(null,studentGradeUpdateWrapper);
                                }
                            }
                        }else if(courseHouse>0){
                            //isAll = false;
                        }
                        //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                        //orderDetailUpdateWrapper.set("residue_course_count",courseHouse);
                        //orderDetailUpdateWrapper.set("residue_price",)
                        //orderDetailMapper.update(null,orderDetailUpdateWrapper);
                        orderDetail.setResidueCourseCount(courseHouse);//设置剩余课时
                        //设置剩余金额
                        BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                        residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                        //返回0表示等于0，返回1表示大于0，返回-1表示小于0
                        if(residuePrice.compareTo(BigDecimal.ZERO) == -1){

                        }
                        orderDetail.setResiduePrice(residuePrice);
                        iOrderDetailService.updateById(orderDetail);
                        //orderDetail.setResiduePrice();
                    }else {
                        throw new CommonException(ResultCode.OUT_COURSE_NOT);
                    }
                }
                iOrderTransferDetailService.save(orderTransferDetail);
            }

            /*if(transferCourseId != null){
                if(isAll == true){
                    //把所在班级设置为转出状态
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("order_detail_id",transferCourseId);
                    //studentGradeQueryWrapper.orderByDesc("created_at");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if(studentGrade != null){
                        studentGrade.setReadingStatus(ReadingStatusEnum.TURN);
                        studentGrade.setStatus(2);
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
            }*/
        }
        //****************************************转课end***********************************//


        //****************************************退费信息详情 start***********************************//
        if(orderType == Code.ORDER_TYPE_REFUND){
            Long refundCourseId = null;
            //Boolean isAll = true;//是否全部退出

            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()){
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id

                //退费
                OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                if(orderDetail!=null){
                    refundCourseId = orderDetail.getId();

                    OrderDetail newOrderDetail = new OrderDetail();
                    newOrderDetail.setId(orderDetail.getId());
                    Integer outCourseHouse =  orderTransferDetail.getOutHouse();
                    Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                    //退费课时不能大于剩余课时
                    if(courseHouse < 0){
                        throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                    }else if(courseHouse == 0){
                        //剩余课时为0，表示全部退出
                        newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);

                        StudentGrade studentGrade = iStudentGradeService.getById(orderDetail.getId());
                        if(studentGrade != null){
                            if(studentGrade.getUseCourseCount() == 0){
                                iStudentSchoolService.removeById(studentGrade);
                            }else {
                                //把所在班级设置为退费状态
                                UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                                //studentGradeUpdateWrapper.set("status",2);
                                studentGradeUpdateWrapper.set("reading_status",ReadingStatusEnum.FINISH.getKey());
                                studentGradeUpdateWrapper.eq("order_detail_id",orderDetail.getId());
                                iStudentGradeService.update(null,studentGradeUpdateWrapper);
                            }
                        }

                        //修改续班状态为退费
                        iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,3).set(RenewClass::getOrderStatus,3));


                    }else if(courseHouse>0){
                        //isAll = false;
                    }

                    //剩余课时
                    newOrderDetail.setResidueCourseCount(courseHouse);//剩余课时
                    BigDecimal outPrice = orderDetail.getOutPrice();//退出金额

                    //累计退出金额
                    BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                    newOrderDetail.setOutPrice(allOutPrice);
                    newOrderDetail.setOutHouse(orderDetail.getOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                    //设置剩余金额
                    BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                    residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                    newOrderDetail.setResiduePrice(residuePrice);
                    orderDetailMapper.updateById(newOrderDetail);
                }else {
                    throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                }
                iOrderTransferDetailService.save(orderTransferDetail);
                //orderTransferDetailList.add(orderTransferDetail);
            }
            /*if(refundCourseId != null){
                if(isAll == true){
                    //把所在班级设置为退费状态
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("course_id",refundCourseId);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if(studentGrade != null){
                        studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                        studentGrade.setStatus(2);
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
            }*/
        }
        //****************************************补费，转课，退费信息详情 end***********************************//



        //*************************************续班率start**************************************************//
        if(renewClassesList.size()>0){
            iRenewClassService.saveBatch(renewClassesList,renewClassesList.size());
        }
        //*************************************续班率end**************************************************//
        orderApply.setTradeContent(tradeContent);
        //this.save(orderApply);
        orderApplyMapper.updateById(orderApply);
        return true;
    }

    public boolean updateDate(OrderApply orderApply){
        OrderApply orderApplyCount = orderApplyMapper.selectById(orderApply.getId());
        if(orderApplyCount == null){
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        UpdateWrapper<OrderApply> orderApplyUpdateWrapper = new UpdateWrapper<>();
        orderApplyUpdateWrapper.eq("id",orderApply.getId());
        orderApplyUpdateWrapper.set("handle_date",orderApply.getHandleDate());
        orderApplyMapper.update(null,orderApplyUpdateWrapper);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id",orderApply.getId());

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
        for (OrderDetail orderDetail:orderDetailList){

            renewDataQueryWrapper.eq("student_id",orderDetail.getStudentId());
            renewDataQueryWrapper.eq("school_id",orderDetail.getSchoolId());
            renewDataQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
            renewDataQueryWrapper.eq("year_part_renew",orderDetail.getYearPart());
            renewDataQueryWrapper.eq("quarter_num_renew",orderDetail.getQuarterNum());

            List<RenewData> renewDataList = iRenewDataService.list(renewDataQueryWrapper);
            for (RenewData renewData:renewDataList){
                if(renewData.getRenewDate()!=null && renewData.getRenewDate().equals(orderDetail.getHandleDate())){
                    renewData.setRenewDate(orderApply.getHandleDate());
                    iRenewDataService.updateById(renewData);
                }
            }
            orderDetail.setHandleDate(orderApply.getHandleDate());
            iOrderDetailService.updateById(orderDetail);
        }
        return true;
    }

    /**
     * 转校
     * @param orderApply
     * @return
     * @throws ParseException
     */
    @Transactional
    public boolean transferSchoolSave(OrderApply orderApply) throws ParseException{

        OrderApply inOrderApply = (OrderApply) orderApply.clone();//转校用的
        OrderApply returnOrderApply = (OrderApply) orderApply.clone();//转校用的

        Integer orderType = returnOrderApply.getOrderType().getKey();
        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        OrderTransfer orderTransfer = returnOrderApply.getOrderTransfer();

        if(orderTransfer.getOutSchoolId().equals(orderTransfer.getInSchoolId())){
            throw new CommonException(ResultCode.SCHOOL_NOT_EQUAL);
        }else {
            //System.out.print(orderTransfer.getOutSchoolId()+"==="+orderTransfer.getInSchoolId());
        }
        Integer outYearPart = 0;
        //****************************************退费信息详情 start***********************************//
        if(orderType == Code.ORDER_TYPE_TRANSFERSCHOOL){
            returnOrderApply.setCostType(2);//1收入，2支出
            returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            returnOrderApply.setSchoolId(orderTransfer.getOutSchoolId());//所属校区
            returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
            returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
            orderApplyMapper.insert(returnOrderApply);



            //转校
            if((orderType == Code.ORDER_TYPE_TRANSFERSCHOOL) && orderTransfer!=null){
                orderTransfer.setOrderId(returnOrderApply.getId());
                iOrderTransferService.save(orderTransfer);
                Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
                tradeContent += "转校退费："+outCourse.getName()+"退"+orderTransfer.getOutHouse()+"课时，应退学费"+orderTransfer.getOutPrice()+"元";
            }
            Long refundCourseId = null;
            //Boolean isAll = true;//是否全部退出



            List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
            Iterator<OrderTransferDetail> orderTransferDetailIterator = returnOrderApply.getOrderTransferDetailList().iterator();
            while (orderTransferDetailIterator.hasNext()){
                OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
                orderTransferDetail.setOrderType(returnOrderApply.getOrderType());
                orderTransferDetail.setOrderId(returnOrderApply.getId());//设置对应的新订单id

                //退费
                OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                outYearPart =orderDetail.getYearPart();
                //System.out.print("orderDetail===");
                //System.out.print(orderDetail);

                if(orderDetail!=null){
                    refundCourseId = orderDetail.getId();

                    OrderDetail newOrderDetail = new OrderDetail();
                    newOrderDetail.setId(orderDetail.getId());

                    Integer outCourseHouse =  orderTransferDetail.getOutHouse();
                    Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                    //退费课时不能大于剩余课时
                    if(courseHouse < 0){
                        throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                    }else if(courseHouse == 0){
                        //剩余课时为0，表示全部退出
                        newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);

                        //把所在班级设置为退费状态
                        UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                        //studentGradeUpdateWrapper.set("status",2);
                        studentGradeUpdateWrapper.set("reading_status",ReadingStatusEnum.RETREAT.getKey());
                        studentGradeUpdateWrapper.eq("order_detail_id",orderDetail.getId());
                        iStudentGradeService.update(null,studentGradeUpdateWrapper);

                        //修改续班状态为退费
                        //iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,3).set(RenewClass::getOrderStatus,3));


                    }else if(courseHouse>0){
                        //isAll = false;
                    }

                    //System.out.print("courseHouse:"+courseHouse);
                    //剩余课时
                    newOrderDetail.setResidueCourseCount(courseHouse);//剩余课时
                    BigDecimal outPrice = orderDetail.getOutPrice();
                    //累计退出金额
                    BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                    newOrderDetail.setOutPrice(allOutPrice);
                    newOrderDetail.setOutHouse(orderDetail.getOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                    //设置剩余金额
                    BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                    residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                    newOrderDetail.setResiduePrice(residuePrice);
                    orderDetailMapper.updateById(newOrderDetail);
                }else {
                    throw new CommonException(ResultCode.REFUND_COURSE_NOT);
                }
                iOrderTransferDetailService.save(orderTransferDetail);
                //orderTransferDetailList.add(orderTransferDetail);
            }
            returnOrderApply.setTradeContent(tradeContent);
            orderApplyMapper.updateById(returnOrderApply);
        }

        //*************************************支付信息start**************************************************//
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        Iterator<OrderPayAccount> orderPayAccountIterator = returnOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()){
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setOrderId(returnOrderApply.getId());
            orderPayAccount.setPrice(orderTransfer.getOutPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if(orderPayAccountList.size()>0){
            iOrderPayAccountService.saveBatch(orderPayAccountList,orderPayAccountList.size());
        }
        //*************************************支付信息end**************************************************//


        //****************************************退费信息详情 end***********************************//

        //*************************************订单详情start**************************************************//
        Long inGradeId = null;
        Integer inCourseHosue = 0;

        tradeContent = "";
        if(orderType == Code.ORDER_TYPE_TRANSFERSCHOOL){

            inOrderApply.setReceiptNo(null);
            inOrderApply.setCostType(1);//1收入，2支出
            inOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
            inOrderApply.setSchoolId(orderTransfer.getInSchoolId());//所属校区

            System.out.print("inOrderApplyId:"+inOrderApply.getId());

            orderApplyMapper.insert(inOrderApply);

            List<StudentGrade> studentGradeList = new ArrayList<>();

            //支付详情
            List<OrderDetail> orderDetailList = new ArrayList<>();
            Iterator<OrderDetail> orderDetailIterator = inOrderApply.getOrderDetailList().iterator();



            while (orderDetailIterator.hasNext()){

                if(orderType == Code.ORDER_TYPE_TRANSFERSCHOOL){
                    if(tradeContent !=""){
                        tradeContent += "</br>";
                    }else {
                        tradeContent += "转校报名：";
                    }
                }

                OrderDetail orderDetail = orderDetailIterator.next();
                inCourseHosue = orderDetail.getAllCourseCount();
                orderDetail.setHandleDate(inOrderApply.getHandleDate());
                orderDetail.setOrderType(inOrderApply.getOrderType());
                orderDetail.setId(idWorker.nextId());
                orderDetail.setStudentId(inOrderApply.getStudentId());
                orderDetail.setUseCourseCount(0);
                orderDetail.setAllCourseCount(orderDetail.getAllCourseCount());//总课时
                orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount());//剩余课时
                orderDetail.setResiduePrice(orderDetail.getSolidPrice());//优惠金额
                //studentGrade.setSchoolId();
                //studentGrade.setEndDate();

                //studentGrade.setAllCourseCount(orderDetail.getAllCourseCount());
                //studentGrade.setUseCourseCount(0);
                //studentGrade.setResidueCourseCount(orderDetail.getAllCourseCount());
                Course course = iCourseService.getById(orderDetail.getCourseId());
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());


                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());

                tradeContent += course.getName()+",";

                //续班信息
                /*RenewClass renewClass = iQuarterService.getRenewForPay(inOrderApply.getStudentId(),orderDetail.getSchoolId(),orderDetail.getSubjectsId(),orderDetail.getCourseId(),orderDetail.getAllCourseCount(),orderType);
                renewClass.setOrderType(inOrderApply.getOrderType().getKey());
                if(renewClass.getReSetIsnew() == 1){
                    orderDetail.setIsNewStudent(1);//设置为新生
                }else {
                    orderDetail.setIsNewStudent(0);
                }*/
                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                orderDetail.setYearPart(year_part);

                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part+""+course.getQuarterNum()));

                Grade grade = null;
                if(orderDetail.getGradeId()!=null){
                    //分班
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setOrderDetailId(orderDetail.getId());
                    studentGrade.setStudentId(inOrderApply.getStudentId());
                    studentGrade.setSubjectsId(course.getSubjectsId());//科目id
                    studentGrade.setGradeId(orderDetail.getGradeId());
                    studentGrade.setCourseId(orderDetail.getCourseId());
                    studentGrade.setYearPart(year_part);///////////////待重新添加
                    studentGrade.setQuarterNum(course.getQuarterNum());

                    //studentGrade.setOrderDetailId(orderDetail.getId());//设置订单id
                    grade = iGradeService.getById(orderDetail.getGradeId());
                    if(grade!=null){
                        inGradeId = grade.getId();
                        orderDetail.setGradeName(grade.getName());
                        orderDetail.setCourseHouse(grade.getStuDeductHour());
                        studentGrade.setSchoolId(grade.getSchoolId());
                        //orderDetail.setSchoolId(grade.getSchoolId());
                        tradeContent += grade.getName()+",";

                        //添加到班级
                        iStudentGradeService.addData(orderDetail.getId(),grade.getSchoolId(),orderApply.getStudentId(),grade.getId(),course.getId(),course.getSubjectsId(),year_part,course.getQuarterNum(),orderDetail.getAllCourseCount());


                        //设置续班老师
                        /*if(orderType == Code.ORDER_TYPE_SiGN){
                            studentGrade.setRenewTeacherId(grade.getTeacherId());
                        }else {
                            //转课
                            if(orderDetail.getAllCourseCount()>3){
                                studentGrade.setRenewTeacherId(grade.getTeacherId());
                            }
                        }*/

                    }
                    studentGradeList.add(studentGrade);
                }

                tradeContent += orderDetail.getPrice();

                if(orderDetail.getCoursePriceId()!=null){
                    CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                    if(coursePricing != null){
                        tradeContent +="("+coursePricing.getCountUnit()+")*"+orderDetail.getCount()+"="+orderDetail.getPrice()+"元";
                        orderDetail.setCoursePriceName(coursePricing.getCount()+coursePricing.getCountUnit()+"="+coursePricing.getPrice()+"元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }
                orderDetail.setOrderId(inOrderApply.getId());

                Long studentId = orderApply.getStudentId();

                UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
                studentUpdateWrapper.eq("id",studentId).set("school_id",orderDetail.getSchoolId());
                iStudentService.update(null,studentUpdateWrapper);

                //renewClass.setOrderDetailId(orderDetail.getId());
                //renewClassesList.add(renewClass);
                //orderDetail.setYearPart(renewClass.getYearPart());
                iOrderDetailService.save(orderDetail);
                //orderDetailList.add(orderDetail);

                //设置为新生或者老生
                //iStudentTypeService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course.getSubjectsId(),orderDetail.getIsNewStudent());

                //更新续班信息是否成功
                //if(orderType == Code.ORDER_TYPE_SiGN){
                    //报名
                //    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),1);
                //}else {
                    //转课
                //    iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),2);

                //}
                //添加当前报读的续班信息
                //iRenewDataService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade);

            }
            iRenewDataService.transferSchoolUpdate(orderApply.getStudentId(),orderTransfer.getOutSchoolId(),outYearPart,orderTransfer.getInSchoolId(),orderTransfer.getOutGradeId(),orderTransfer.getInGradeId(),inGradeId,inCourseHosue);

            if(orderDetailList.size()>0){
                //为了添加交易内容，放在上面一条一条加
                //iOrderDetailService.saveBatch(orderDetailList,orderDetailList.size());
            }
            if(studentGradeList.size()>0){
                iStudentGradeService.saveBatch(studentGradeList,studentGradeList.size());
            }
        }

        //*************************************支付信息start**************************************************//
        orderPayAccountList = new ArrayList<>();
        orderPayAccountIterator = inOrderApply.getOrderPayAccountList().iterator();
        while (orderPayAccountIterator.hasNext()){
            OrderPayAccount orderPayAccount = orderPayAccountIterator.next();
            orderPayAccount.setId(null);
            orderPayAccount.setOrderId(inOrderApply.getId());
            orderPayAccount.setPrice(inOrderApply.getPrice());
            orderPayAccountList.add(orderPayAccount);
        }
        if(orderPayAccountList.size()>0){
            iOrderPayAccountService.saveBatch(orderPayAccountList,orderPayAccountList.size());
        }
        inOrderApply.setTradeContent(tradeContent);
        orderApplyMapper.updateById(inOrderApply);
        //*************************************支付信息end**************************************************//

        //****************************************报名信息详情 end***********************************//


        return true;
    }

    //public void

    public boolean updateTo(OrderApply orderApply){
        this.updateById(orderApply);
        //System.out.print("insertId:"+orderApply.getId());
        List<OrderDetail> orderDetailList = new ArrayList<>();

        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        List<OrderPayAccount> updateOrderPayAccountList = new ArrayList<>();

        Iterator<OrderDetail> orderDetailIterator = orderApply.getOrderDetailList().iterator();
        while (orderDetailIterator.hasNext()){
            OrderDetail orderDetail = orderDetailIterator.next();
            orderDetail.setResidueCourseCount(orderDetail.getAllCourseCount() - orderDetail.getUseCourseCount());
            orderDetail.setOrderType(orderApply.getOrderType());
            if(orderDetail.getCoursePriceId()!=null){
                CoursePricing coursePricing = iCoursePricingService.getById(orderDetail.getCoursePriceId());
                if(coursePricing!=null){
                    orderDetail.setCoursePriceName(coursePricing.getCount()+coursePricing.getCountUnit()+"="+coursePricing.getPrice()+"元");
                }
            }
            if(orderDetail.getId()!=null){
                orderDetailList.add(orderDetail);
            }

        }

        Iterator<OrderPayAccount> orderPayAccountIterator = orderApply.getOrderPayAccountList().iterator();
        while (orderDetailIterator.hasNext()){
            OrderPayAccount orderPayAccount = new OrderPayAccount();
            if(orderPayAccount.getId()!= null && orderPayAccount.getId()!=0){
                updateOrderPayAccountList.add(orderPayAccount);
            }else {
                orderPayAccountList.add(orderPayAccount);
            }
        }

        if(orderDetailList.size()>0){
            iOrderDetailService.updateBatchById(orderDetailList,orderDetailList.size());
        }
        if(orderPayAccountList.size()>0){
            iOrderPayAccountService.saveBatch(orderPayAccountList,orderPayAccountList.size());
        }
        if(updateOrderPayAccountList.size()>0){
            iOrderPayAccountService.updateBatchById(updateOrderPayAccountList,updateOrderPayAccountList.size());
        }
        return true;
    }

    public IPage<OrderApply> findAll(IPage<?> page, Wrapper wrapper){
        return orderApplyMapper.findAll(page,wrapper);
    }

    public List<Map<String,Object>> orderArrears(Wrapper wrapper){
        return orderApplyMapper.orderArrears(wrapper);
    }


    /**
     * 收支明细
     * @param page
     * @param wrapper
     * @return
     */
    public IPage<OrderApply> expensesAndReceipts(IPage<?> page, Wrapper wrapper){
        return orderApplyMapper.expensesAndReceipts(page,wrapper);
    }

    public IPage<ResTransaction> transaction(IPage<?> page, Wrapper wrapper){

        IPage<ResTransaction> iPage = orderApplyMapper.transaction(page,wrapper);
        for (ResTransaction resTransaction:iPage.getRecords()){
            resTransaction.setSubjectsName(subjectsMapper.getName(resTransaction.getSubjectsId()));
        }

        return iPage;
    }

    public IPage<OrderApply> affirmIncome(IPage<?> page,Wrapper wrapper){
        return orderApplyMapper.affirmIncome(page,wrapper);
    }

    /**
     * 确认到帐
     * @param id
     * @param adminId 登陆人id
     * @param isSuper 是否超级管理员
     * @return
     */
    @Transactional
    public boolean confirmArrive(Long id,Long adminId,Integer isSuper){
        OrderApply orderApply = this.getById(id);
        Integer rs = 1;
        if(orderApply == null){
            throw new CommonException(ResultCode.NOORDER);
        }else {
            orderApply.setStatus(StatusOrderApplyEnum.CONFIRM);
            orderApply.setArriveAffirm(ArriveAffirmEnum.CONFIRM);
            orderApply.setPrincipalDate(LocalDateTime.now());
            this.updateById(orderApply);
            LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId,id).set(OrderDetail::getStatus,StatusOrderApplyEnum.CONFIRM).set(OrderDetail::getArriveAffirm,ArriveAffirmEnum.CONFIRM);
            orderDetailMapper.update(null,orderDetailLambdaUpdateWrapper);
        }
        return true;
    }


    /**
     *财务确认到帐
     * @param id
     * @param adminId
     * @param isSuper
     * @return
     */
    public boolean financeConfirm(Long id,Long adminId,Integer isSuper){
        OrderApply orderApply = this.getById(id);
        Integer rs = 1;
        if(orderApply == null){
            throw new CommonException(ResultCode.NOORDER);
        }else {
            //orderApply.setStatus(StatusOrderApplyEnum.CONFIRM);
            if(orderApply.getArriveAffirm().getKey()==0){
                throw new CommonException(ResultCode.SCHOOL_AFIRM);
            }
            orderApply.setArriveAffirm(ArriveAffirmEnum.TOVOID);
            orderApply.setFinanceDate(LocalDateTime.now());
            this.updateById(orderApply);
            LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId,id).set(OrderDetail::getArriveAffirm,ArriveAffirmEnum.TOVOID);
            orderDetailMapper.update(null,orderDetailLambdaUpdateWrapper);
        }
        return true;
    }


    /**
     * 订单作废
     * @param id
     * @param adminId 登陆人id
     * @param isSuper 是否超级管理员
     * @return
     */
    @Transactional
    public boolean invalidate(Long id,Long adminId,Integer isSuper){
        OrderApply orderApply = this.getById(id);
        if(orderApply == null){
            throw new CommonException(ResultCode.NOORDER);
        }else {

            Integer useHouseCount = orderDetailMapper.getUseHouseForOrderId(orderApply.getId());

            if(orderApply.getStatus() == StatusOrderApplyEnum.CONFIRM){
                throw new CommonException(ResultCode.NOTINVALIDATE);
            }else if(useHouseCount>0){
                throw new CommonException(ResultCode.NOTINVALIDATEUSE);
            }else if(orderApply.getStatus() == StatusOrderApplyEnum.TOVOID){
                throw new CommonException(ResultCode.SUCCESS);
            }

            orderApply.setStatus(StatusOrderApplyEnum.TOVOID);
            this.updateById(orderApply);

            //更新报读详情的状态
            LambdaUpdateWrapper<OrderDetail> orderDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderDetailLambdaUpdateWrapper.eq(OrderDetail::getOrderId,id).set(OrderDetail::getStatus,StatusOrderApplyEnum.TOVOID);
            orderDetailMapper.update(null,orderDetailLambdaUpdateWrapper);


            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id",id));
            for (OrderDetail orderDetail:orderDetailList){
                //iRenewClassService.update(null,new LambdaUpdateWrapper<RenewClass>().eq(RenewClass::getOrderDetailId,orderDetail.getId()).set(RenewClass::getStatus,2).set(RenewClass::getOrderStatus,2));
                iRenewDataService.deleteData(orderDetail.getSchoolId(),orderDetail.getStudentId(),orderDetail.getSubjectsId(),orderDetail.getYearPart(),orderDetail.getQuarterNum());
                //更新报读班级的状态
                LambdaUpdateWrapper<StudentGrade> studentGradeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                studentGradeLambdaUpdateWrapper.eq(StudentGrade::getOrderDetailId,orderDetail.getId()).set(StudentGrade::getStatus,3);
                iStudentGradeService.update(null,studentGradeLambdaUpdateWrapper);
                iRenewDataService.deleteData(orderDetail.getSchoolId(),orderDetail.getStudentId(),orderDetail.getSubjectsId(),orderDetail.getYearPart(),orderDetail.getQuarterNum());

            }

            //订单类型：1报名，2补费，3转课，4退费，5转校
            if(orderApply.getOrderType().getKey() == 1){

            }else if(orderApply.getOrderType().getKey() == 2){

            }else if(orderApply.getOrderType().getKey() == 3){
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id",orderApply.getId()));
                for (OrderTransferDetail orderTransferDetail:orderTransferDetailList){
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                    BigDecimal outPrice = orderTransferDetail.getOutPrice();
                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);
                    if(residuePrice.compareTo(orderDetail.getPrice())<=0){
                        orderDetail.setResiduePrice(residuePrice);
                    }
                    iOrderDetailService.updateById(orderDetail);
                }
            }else if(orderApply.getOrderType().getKey() == 4){
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id",orderApply.getId()));
                for (OrderTransferDetail orderTransferDetail:orderTransferDetailList){
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                    BigDecimal outPrice = orderTransferDetail.getOutPrice();
                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);
                    if(residuePrice.compareTo(orderDetail.getPrice())<=0){
                        orderDetail.setResiduePrice(residuePrice);
                    }
                    iOrderDetailService.updateById(orderDetail);
                }
            }else if(orderApply.getOrderType().getKey() == 5){
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id",orderApply.getId()));
                for (OrderTransferDetail orderTransferDetail:orderTransferDetailList){
                    OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + orderTransferDetail.getOutHouse());
                    BigDecimal outPrice = orderTransferDetail.getOutPrice();
                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(outPrice);
                    if(residuePrice.compareTo(orderDetail.getPrice())<=0){
                        orderDetail.setResiduePrice(residuePrice);
                    }
                    iOrderDetailService.updateById(orderDetail);
                }
            }

        }
        return true;
    }

    @Override
    public List<Reconciliation> reconciliationRate(String yearPart, String quarterNum, String subjectsId, String startDate, String endDate) {
        return orderApplyMapper.reconciliationRate(yearPart,quarterNum,subjectsId,startDate,endDate);
    }

    @Override
    public IPage<Reconciliation> reconciliationDetails(IPage<Reconciliation> page,String yearPart, String quarterNum, String subjectsId, String startDate, String endDate, String schoolId, String status) {
        return orderApplyMapper.reconciliationDetails(page,yearPart,quarterNum,subjectsId,startDate,endDate,schoolId,status);
    }
}
